//
//  FWPhtoGroupView.m
//  BirdLoveSheep
//
//  Created by wwj on 16/3/23.
//  Copyright © 2016年 wwj. All rights reserved.
//

#import "FWPhotoGroupView.h"
#import "FWTopicModel.h"
#import <UIImageView+WebCache.h>
#import "FWProgressRingView.h"

#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height

@interface FWPhotoGroupView ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollerView;
@property (weak, nonatomic) IBOutlet FWProgressRingView *progressView;
@property (weak, nonatomic) UIImageView *imageView;

@property (assign, nonatomic) CGPoint beginPoint;
@property (assign, nonatomic) CGRect newFrame;
@end

@implementation FWPhotoGroupView

+ (instancetype)photoGroupView{
    return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] lastObject];
}

- (void)awakeFromNib{
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidden)];
    [self addGestureRecognizer:tap];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
    tap2.numberOfTapsRequired = 2;
    [tap requireGestureRecognizerToFail:tap2];
    [self addGestureRecognizer:tap2];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
    [self addGestureRecognizer:pan];
    
    self.scrollerView.delegate = self;
    self.scrollerView.maximumZoomScale = 2.0;
    self.scrollerView.multipleTouchEnabled = YES;
    
}

- (void)setFrame:(CGRect)frame{
    frame = CGRectMake(0, 0, kScreenW, kScreenH);
    [super setFrame:frame];
}

- (void)show:(UIView *)view{
    self.newFrame = [view.superview convertRect:view.frame toView:nil];
    UIWindow *windown = [UIApplication sharedApplication].keyWindow;
    self.alpha = 0.0;
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 1.0;
    }];
    [windown addSubview:self];
}

- (void)hidden{
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 0.0;
        self.imageView.frame = self.newFrame;
    }completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
    
}

- (void)setModel:(FWTopicModel *)model{
    _model = model;
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = self.newFrame;
    [self.scrollerView addSubview:imageView];
    self.imageView = imageView;
    CGFloat picW = kScreenW;
    CGFloat picH = kScreenW / model.width * model.height;
    
    if (picH > kScreenH) {
        self.scrollerView.contentSize = CGSizeMake(0, picH);
        [UIView animateWithDuration:DURATION animations:^{
            imageView.frame = CGRectMake(0, 0, picW, picH);
        }];
        
    }else {
        imageView.size = CGSizeMake(picW, picH);
        [UIView animateWithDuration:DURATION animations:^{
            imageView.center = CGPointMake(kScreenW * 0.5, kScreenH *0.5);
            MyLog(@"cent2:%@", NSStringFromCGPoint(imageView.center));
        }];
    }
    
    [self.progressView setProgress:model.progress animated:YES];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.image2] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        CGFloat progress = 1.0 * receivedSize / expectedSize;
        [self.progressView setProgress:progress animated:YES];
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.progressView.hidden = YES;
    }];
    
    [self bringSubviewToFront:self.progressView];
    if (imageView.image) {
        self.progressView.hidden = YES;
    }else{
        self.progressView.hidden = NO;
    }
    
}

- (void)doubleTap:(UITapGestureRecognizer *)tap{
    if (self.scrollerView.zoomScale > 1.0) {
        [self.scrollerView setZoomScale:1.0 animated:YES];
    }else {
        CGPoint touchPoint = [tap locationInView:self.imageView];
        CGFloat newZoomScale = self.scrollerView.maximumZoomScale;
        CGFloat xsize = self.width / newZoomScale;
        CGFloat ysize = self.height / newZoomScale;
        [self.scrollerView zoomToRect:CGRectMake(touchPoint.x - xsize * 0.5, touchPoint.y - ysize * 0.5, xsize, ysize) animated:YES];
        
    }
}

- (void)panGesture:(UIPanGestureRecognizer *)pan{
    CGPoint point = [pan locationInView:self];
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
            self.beginPoint = point;
            break;
            
        case UIGestureRecognizerStateChanged:{
            CGPoint vp = [pan velocityInView:self];
            CGFloat deta = point.y - self.beginPoint.y;
            self.scrollerView.y = deta;
            CGFloat alpha = (900 - fabs(deta)) / 900;
            
            [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionCurveLinear animations:^{
                self.alpha = alpha;
            } completion:nil];
            MyLog(@"alpha:%f, deta:%f, vp:%f", alpha, fabs(deta), vp.y);
        }
            break;
            
        case UIGestureRecognizerStateEnded:{
            CGFloat deta = point.y - self.beginPoint.y;
            if (fabs(deta) > 200) {
                [self hidden];
            }else {
                [UIView animateWithDuration:DURATION animations:^{
                    self.scrollerView.y = 0.0;
                    self.alpha = 1.0;
                }];
            }
        }
            break;
            
        case UIGestureRecognizerStateCancelled:
            MyLog(@"UIGestureRecognizerStateEnded");
            break;
            
        case UIGestureRecognizerStateFailed:
            MyLog(@"UIGestureRecognizerStateFailed");
            break;
            
        case UIGestureRecognizerStatePossible:
            MyLog(@"UIGestureRecognizerStatePossible");
            break;
            
    }

}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    UIView *subView = self.imageView;
    
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    
    subView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                 scrollView.contentSize.height * 0.5 + offsetY);
}

@end
